package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author chencfgs
 * @date 2019-12-10 0:00
 */

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference(timeout = 2000)
    private ReportService reportService;

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;


    //getBusinessReportData
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
//            String string = JSON.toJSONString();
//            ObjectMapper
//            String encode = URLEncoder.encode(filename, "UTF-8");
            Map<String, Object> map = reportService.getBusinessReportData();
            String template = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms‐excel");
            response.setHeader("content-disposition", "attachment;filename=report_template.xlsx");
            ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(template).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照下一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(map, fillConfig, writeSheet);
            excelWriter.fill(map.get("hotSetmeal"), fillConfig, writeSheet);
            excelWriter.finish();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //exportBusinessReport
//    @RequestMapping("/exportBusinessReport")
//    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        try {
//            Map<String, Object> result = reportService.getBusinessReportData();
//            String reportDate = (String) result.get("reportDate");
//            Integer todayNewMember = (Integer) result.get("todayNewMember");
//            Integer totalMember = (Integer) result.get("totalMember");
//            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
//            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
//            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
//            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
//            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
//            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
//            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
//            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
//            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");
//
//            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
//            XSSFWorkbook execel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
//            XSSFSheet sheet = execel.getSheetAt(0);
//            sheet.getRow(2).getCell(5).setCellValue(reportDate);
//
//            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
//            sheet.getRow(4).getCell(7).setCellValue(totalMember);
//
//            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
//            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
//
//            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
//            sheet.getRow(7).getCell(5).setCellValue(todayVisitsNumber);
//
//            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
//            sheet.getRow(8).getCell(5).setCellValue(thisWeekVisitsNumber);
//
//            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
//            sheet.getRow(9).getCell(5).setCellValue(thisMonthVisitsNumber);
//
//            int rowNum = 12;
//            for (Map<String, Object> map : hotSetmeal) {
//                String name = (String) map.get("name");
//                Long setmeal_count = (Long) map.get("setmeal_count");
//                BigDecimal proportion = (BigDecimal) map.get("proportion");
//
//                XSSFRow row = sheet.getRow(rowNum++);
//                row.getCell(4).setCellValue(name);
//                row.getCell(5).setCellValue(setmeal_count);
//                row.getCell(6).setCellValue(proportion.doubleValue());
//            }
//            //String fileName = TestFileUtil.getPath() + "write" + System.currentTimeMillis() + ".xlsx";
//            // 这里 需要指定写用哪个class去读，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
//            // 如果这里想使用03 则 传入excelType参数即可
//            //EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());
//            ServletOutputStream out = response.getOutputStream();
//            response.setContentType("application/vnd.ms‐excel");
//            response.setHeader("content-disposition", "attachment;filename=report_template.xlsx");
//            execel.write(out);
//
//            out.flush();
//            out.close();
//            execel.close();
//            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
//        }
//    }

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);

        System.out.println(calendar.getTime());

        List<String> list = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            list.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("months", list);

        List<Integer> memberCount = memberService.findMemberCountByMonth(list);
        map.put("memberCount", memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //getSetmealReport
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        try {
            Map<String, Object> map = new HashMap<>();
            //setmealCount
            List<Map<String, Object>> mapList = setmealService.findSetmealCount();
            //setmealNames
            List<String> list = new ArrayList<>();
            for (Map<String, Object> namemap : mapList) {
                String name = (String) namemap.get("name");
                list.add(name);
            }

            map.put("setmealNames", list);
            map.put("setmealCount", mapList);

            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS);

        }
    }


//    try {
//        Map map = reportService.getMemberReport();
//        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
//
//    } catch (Exception e) {
//        e.printStackTrace();
//        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
//    }
}
